package com.kawins.mina.core;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.http.api.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kawins.mina.net.HttpRequestMessage;
import com.kawins.mina.net.HttpResponseMessage;

public class MinaIoHandler extends IoHandlerAdapter {

	private Logger log = LoggerFactory.getLogger(this.getClass());

	/**
	 * 设置sesison超时时间(60s)
	 */
	@Override
	public void sessionOpened(IoSession session) throws Exception {
		session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60);
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		log.info("Access to the request from [" + session.getRemoteAddress() + "]");
		HttpRequestMessage httpRequest = (HttpRequestMessage) message;
		String key = "/" + httpRequest.getContext();
		HttpResponseMessage response;
		MethodInvoker invoker = UriMapping.getInstance().getMethod(key);
		if (null == invoker) {
			response = new HttpResponseMessage();
			log.info("There is no request mapping [" + httpRequest.getContext() + "]");
		} else {
			response = new HttpResponseMessage();
			boolean result = invoker.invoke(httpRequest, response);
			if (!result) {
				response.setResponseCode(HttpStatus.SERVER_ERROR_SERVICE_UNAVAILABLE.code());
			}
		}
		session.write(response);
	}

	/**
	 * 
	 */
	@Override
	public void sessionIdle(IoSession session, IdleStatus status) {
		log.info("The connection from [" + session.getRemoteAddress() + "] into the idle state");
		if (session != null) {
			session.close(true);
		}
	}

	/**
	 * 发生异常处理的事情(关闭session)
	 */
	@Override
	public void exceptionCaught(IoSession session, Throwable cause) {
		log.info("An exception occurs [" + cause.getMessage() + "]");
		if (session != null) {
			session.close(true);
		}
	}
}
